package com.fastloan.safe.mgt.user.controller;

import com.fastloan.safe.core.param.RoleTypeEnum;
import com.fastloan.safe.core.perms.Licensing;
import com.fastloan.safe.core.util.ManagerKit;
import com.fastloan.safe.mgt.auth.model.CmuRole;
import com.fastloan.safe.mgt.auth.service.CmuRoleService;
import com.fastloan.safe.mgt.org.model.CmuOrg;
import com.fastloan.safe.mgt.org.service.CmuOrgService;
import com.fastloan.safe.mgt.root.model.CmDefRole;
import com.fastloan.safe.mgt.root.service.CmDefRoleService;
import com.fastloan.safe.mgt.sys.service.CmSysFileService;
import com.fastloan.safe.mgt.user.model.CmuUser;
import com.fastloan.safe.mgt.user.service.CmuUserService;
import com.fastloan.safe.mgt.user.utils.UserUtil;
import com.kawins.base.baseabs.BaseController;
import com.kawins.result.ResultEnum;
import com.kawins.result.ResultTo;
import com.kawins.spring.valid.core.BeanValid;
import com.kawins.spring.valid.group.Group;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

/**
 * 用户Controller
 *
 * @author rankai
 *         createTime 2017-09-2017/9/25 16:39
 */
@RestController
@RequestMapping("/api/web/user")
public class UserController extends BaseController<CmuUser> {

    @Autowired
    private CmuUserService userService;

    @Autowired
    private CmuRoleService roleService;

    @Autowired
    private CmDefRoleService defRoleService;

    @Autowired
    private CmuOrgService orgService;

    @Autowired
    private CmSysFileService sysFileService;

    /**
     * 修改密码
     *
     * @param oldPwd
     * @param newPwd
     * @return
     */
    @PutMapping("/changePwd")
    @RequiresUser
    public ResultTo changePwd(String userId, String oldPwd, String newPwd) {
        if (StringUtils.isBlank(userId) || StringUtils.isBlank(oldPwd) || StringUtils.isBlank(newPwd)) {
            return new ResultTo(ResultEnum.PARAM_ERROR);
        }
        if (userService.changePwd(userId, oldPwd, newPwd)) {
            return new ResultTo();
        }
        return new ResultTo(ResultEnum.OPERATION_FAILED, "原密码错误");
    }

    /**
     * 获取当前用户基本信息
     *
     * @return
     */
    @GetMapping("/user/info")
    @RequiresUser
    public ResultTo userInfo() {
        ResultTo resultTo = new ResultTo()
                .setData("userBean", ManagerKit.getUser())
                .setData("topOrgId", ManagerKit.getTopOrgId())
                .setData("role", ManagerKit.getRole());
        String userProfile = ManagerKit.getUser().getUserProfile();
        if (StringUtils.isNotBlank(userProfile)) {
            resultTo.setData("userLogo", sysFileService.selectByPrimaryKey(ManagerKit.getUser().getUserProfile()));
        }
        String orgId = ManagerKit.getOrgId();
        if (orgId != null) {
            CmuOrg cmuOrg = orgService.selectByPrimaryKey(orgId);
            resultTo.setData("orgId", orgId)
                    .setData("orgLogo", cmuOrg != null ? cmuOrg.getProfile() : null);
        }
        return resultTo;
    }

    /**
     * 获取普用户列表
     *
     * @return
     */
    @RequestMapping("/pageList")
    public ResultTo pageList() {
        return dataPage("cmuUserPageListByOrgId")
                .setData("orgTree", orgService.selectSonByTop(ManagerKit.getOrgId(), true, true));
    }

    /**
     * 更新或者增加用户,页面数据
     *
     * @param userId
     * @return
     */
    @GetMapping("/param")
    public ResultTo param(@RequestParam(required = false) String userId) {
        Map<String, Object> map = new HashMap<>(0);
        Integer indexType = ManagerKit.getRole().getIndexType();
        if (indexType.equals(RoleTypeEnum.ADMIN.getCode())) {
            map.put("roleList", roleService.select(new CmuRole().setTopOrgId(ManagerKit.getTopOrgId())));
        } else {
            Example example = new Example(CmuRole.class);
            Set<Integer> set = new HashSet<>(0);
            set.add(RoleTypeEnum.AUDITOR.getCode());
            set.add(RoleTypeEnum.MANAGER.getCode());
            example.createCriteria().andEqualTo("topOrgId", ManagerKit.getTopOrgId())
                    .andIn("indexType", set);
            map.put("roleList", roleService.selectByExample(example));
        }
        map.put("orgTree", orgService.selectSonByTop(ManagerKit.getOrgId(), true, true));
        if (StringUtils.isBlank(userId)) {

        } else {
            CmuUser cmuUser = adaptService.selectByPrimaryKey(userId);
            map.put("user", cmuUser);
            map.put("userLogo", sysFileService.selectByPrimaryKey(cmuUser.getUserProfile()));
            map.put("userOrg", orgService.selectByPrimaryKey(orgService.selectOrgByUser(userId)));
            map.put("userRole", roleService.selectByUserId(userId));
            map.put("identityFront", sysFileService.selectByPrimaryKey(cmuUser.getIdentityFront()));
            map.put("identitySide", sysFileService.selectByPrimaryKey(cmuUser.getIdentitySide()));
        }
        return new ResultTo().setData(map);
    }

    /**
     * 增加User
     *
     * @param user
     * @param bindingResult
     * @param roleIds
     * @param logoFile
     * @return
     */
    @PostMapping
    public ResultTo insert(CmuUser user, BindingResult bindingResult, String[] roleIds,
                           @RequestParam String orgId, MultipartFile logoFile,
                           MultipartFile identityFront, MultipartFile identitySide) {
        if (roleIds == null || roleIds.length == 0) {
            return new ResultTo(ResultEnum.PARAM_ERROR, "角色不能为空");
        }
        if (StringUtils.isBlank(orgId)) {
            return new ResultTo(ResultEnum.PARAM_ERROR, "机构不能为空");
        }
        user.setRootRoleId(null);
        userService.insertWithRole(user, roleIds, orgId, false, logoFile, identityFront, identitySide);
        return new ResultTo();
    }

    /**
     * 更新用户信息
     *
     * @param user
     * @param bindingResult
     * @param roleIds
     * @param logoFile
     * @return
     */
    @PutMapping
    public ResultTo update(CmuUser user, BindingResult bindingResult, String[] roleIds, MultipartFile logoFile) {
        if (roleIds == null || roleIds.length == 0) {
            return new ResultTo(ResultEnum.PARAM_ERROR, "角色不能为空");
        }
        user.setRootRoleId(null);
        userService.updateWithRole(user, roleIds, logoFile, false);
        return new ResultTo();
    }

    /**
     * 获取用户所有fun
     *
     * @param userId
     * @return
     */
    @GetMapping("/{userId}")
    public ResultTo paramUserFun(@PathVariable String userId) {
        return new ResultTo().setData(userService.paramUserFun(userId));
    }

    /**
     * 更新用户fun
     *
     * @param userId
     * @return
     */
    @PutMapping("/userFun")
    public ResultTo updateUserFun(@RequestParam String userId, String[] funIds) {
        if (funIds == null || funIds.length == 0) {
            return new ResultTo(ResultEnum.PARAM_ERROR, "用户Fun不能为空");
        }
        userService.updateUserFun(userId, funIds);
        return new ResultTo();
    }


    /**
     * 删除用户
     *
     * @param userId
     * @return
     */
    @DeleteMapping("/{userId}")
    public ResultTo delete(@PathVariable String userId) {
        adaptService.deleteByPrimaryKey(userId);
        return new ResultTo();
    }


    /**
     * 获取系统户列表
     *
     * @return
     */
    @RequestMapping("/pageList/sys")
    @RequiresPermissions("all:/web/user/pageList/sys")
    @Licensing({"add#post:/web/user/sys", "update#put:/web/user/sys", "del#delete:/web/user/userId/sys"})
    public ResultTo pageListSys() {
        Map<String, Object> map = new HashMap<>(0);
        map.put("isAdmin", true);
        return dataPage("cmuUserPageList", map);
    }


    /**
     * 增加或者修改用户页面参数
     *
     * @param userId
     * @return
     */
    @GetMapping("/param/sys")
    @RequiresPermissions(value = {"post:/web/user/sys", "update#put:/web/user/sys"}, logical = Logical.OR)
    public ResultTo paramSys(@RequestParam(required = false) String userId) {
        Map<String, Object> map = new HashMap<>(0);
        map.put("sysRole", defRoleService.select(new CmDefRole().setIsAdmin(1)));
        if (StringUtils.isBlank(userId)) {
        } else {
            map.put("user", adaptService.selectByPrimaryKey(userId));
        }
        return new ResultTo().setData(map);
    }

    /**
     * 增加User
     *
     * @param user
     * @return
     */
    @PostMapping("/sys")
    @BeanValid
    @RequiresPermissions("post:/web/user/sys")
    public ResultTo insertSys(@Validated(Group.Insert.class) CmuUser user, BindingResult bindingResult, String[] roleIds) {
        if (roleIds == null || roleIds.length != 1) {
            return new ResultTo(ResultEnum.PARAM_ERROR, "角色选择错误");
        }
        ResultTo resultTo = UserUtil.validExistUserBean(user, userService, false);
        if ((int) resultTo.get("code") == ResultEnum.OPERATION_FAILED.getCode()) {
            return resultTo;
        }
        userService.insertWithRole(user, roleIds, null, true);
        return new ResultTo();
    }

    /**
     * 更新系统用户
     *
     * @param user
     * @param bindingResult
     * @param roleIds
     * @return
     */
    @PutMapping("/sys")
    @RequiresPermissions("put:/web/user/sys")
    public ResultTo updateSys(@Validated(Group.Update.class) CmuUser user, BindingResult bindingResult,
                              String[] roleIds) {
        if (roleIds == null || roleIds.length != 1) {
            return new ResultTo(ResultEnum.OPERATION_FAILED, "角色选择错误");
        }
        user.setUsername(null);
        ResultTo resultTo = UserUtil.validExistUserBean(user, userService, true);
        if ((int) resultTo.get("code") == ResultEnum.OPERATION_FAILED.getCode()) {
            return resultTo;
        }
        userService.updateWithRole(user, roleIds, null, true);
        return new ResultTo();
    }

    /**
     * 删除系统用户
     *
     * @param userId
     * @return
     */
    @DeleteMapping("/{userId}/sys")
    @RequiresPermissions("delete:/web/user/userId/sys")
    public ResultTo deleteSys(@PathVariable String userId) {
        CmuUser cmuUser = adaptService.selectByPrimaryKey(userId);
        if ("root".equals(cmuUser.getUsername())) {
            return new ResultTo(ResultEnum.OPERATION_FAILED, "Root用户不能删除");
        }
        userService.deleteByPrimaryKey(userId);
        return new ResultTo();
    }

    /**
     * userBean校验接口
     *
     * @param user
     * @return
     */
    @PostMapping("/valid")
    public ResultTo validUserBean(CmuUser user) {
        return UserUtil.validExistUserBean(user, userService, false);
    }

    /**
     * 更新密码
     *
     * @param oldPwd
     * @param newPwd
     * @return
     */
    @PutMapping("/updatePwd")
    @RequiresUser
    public ResultTo update(@RequestParam String oldPwd, @RequestParam String newPwd) {
        return userService.updatePwd(oldPwd, newPwd);
    }

    /**
     * 根据类型更新用户信息
     *
     * @param updateType 1:重置密码  2:锁定/解锁
     * @param user
     * @return
     */
    @PutMapping("/{updateType}")
    public ResultTo update(@PathVariable Integer updateType, CmuUser user) {
        return userService.update(updateType, user);
    }

    /**
     * 变更身份证
     *
     * @param userId
     * @param identityFront
     * @param identitySide
     * @return
     */
    @PutMapping("/changeIdentity/{userId}")
    public ResultTo changeIdentity(@PathVariable String userId, MultipartFile identityFront, MultipartFile identitySide) {
        userService.uploadIdentity(userId, identityFront, identitySide);
        return new ResultTo();
    }
}
